var targetHeight = 742.0;
var ImageOrientationFix=function(opts){
    var settings={
        //img:"" //图片元素，推荐用var _img=new Image() 然后用_img.onload=function(){ EXIF.getData(this,function(exifdata){});_img.src=value; }这样使用。
        image:"" //分成三种类型，一种是服务端的url，一种是base64数据，还有一种是iamge原生元素。
        ,imgType:"url" //url，base64或者image
        ,onFix:function(base64ImgStr){

        }//处理以后得到的base64字符串。
    };

    var _exifInfo={};
    var _realImage="";

    $.extend(settings,opts);

    //---修正ios压扁问题。
//--修正ios下面canvas图片压缩的情况。
    /**
     * Detecting vertical squash in loaded image.
     * Fixes a bug which squash image vertically while drawing into canvas for some images.
     * This is a bug in iOS6 devices. This function from https://github.com/stomita/ios-imagefile-megapixel
     *
     */
    function detectVerticalSquash(img) {
        var iw = img.naturalWidth, ih = img.naturalHeight;
        var canvas = document.createElement('canvas');
        canvas.width = 1;
        canvas.height = ih;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);
        var data = ctx.getImageData(0, 0, 1, ih).data;
        // search image edge pixel position in case it is squashed vertically.
        var sy = 0;
        var ey = ih;
        var py = ih;
        while (py > sy) {
            var alpha = data[(py - 1) * 4 + 3];
            if (alpha === 0) {
                ey = py;
            } else {
                sy = py;
            }
            py = (ey + sy) >> 1;
        }
        var ratio = (py / ih);
        return (ratio===0)?1:ratio;
    }

    /**
     * A replacement for context.drawImage
     * (args are for source and destination).
     */
    function drawImageIOSFix(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) {
        var vertSquashRatio =detectVerticalSquash(img);
        // Works only if whole image is displayed:
        // ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio);
        // The following works correct also when only a part of the image is displayed:
        ctx.drawImage(img, sx * vertSquashRatio, sy * vertSquashRatio,
            sw * vertSquashRatio, sh * vertSquashRatio,
            dx, dy, dw, dh );
    }


    // 742

    var _app={
        init:function(){
            var __image = new Image();
            var _me=this;
            _realImage=__image;

            __image.onload = function () {
                EXIF.getData(this, function () {

                    _exifInfo = EXIF.getAllTags(this);
                    _me.__fix();
                });
            };
            if(settings.imgType=="image"){
                __image.src=$(settings.image).attr("src");
            }
            else{
                __image.src=settings.image;
            }
        },
        _scale: function (_context,_canvas) {
            if(_canvas.height> targetHeight){
                var scale = targetHeight/_canvas.height ;
                console.log(scale);
                _canvas.width = _canvas.width*scale;
                _canvas.height = targetHeight;
                _context.scale(scale,scale);
            }
        }
        ,__fix:function(){

            //--修正ios6 7 颠倒，压扁问题。

            var Options={
                width:_realImage.naturalWidth
                ,height:_realImage.naturalHeight
                ,transX:0
                ,transY:0
                ,XDimension:0
                ,YDimension:0
                ,Orientation:1
            };
            Options.Orientation=_exifInfo.Orientation;

            if(Options.Orientation==undefined){
                Options.Orientation=1;
            }

            var _realWidth=0;
            var _realHeight=0;
            //--计算是否需要旋转。
            if(Options.Orientation!=1){
                Options.transX=parseInt(Options.width/2);
                Options.transY=parseInt(Options.height/2);

            }
            else{
                Options.transX=0;
                Options.transY=0;

            }
            _realWidth=_realImage.width;
            _realHeight=_realImage.height;

            var XDimension=_exifInfo["PixelXDimension"];// EXIF.getTag(this,"PixelXDimension");
            var YDimension=_exifInfo["PixelYDimension"]; // EXIF.getTag(this,"PixelYDimension");
            Options.XDimension=XDimension;
            Options.YDimension=YDimension;

            var tmpCanvas=document.createElement("canvas");

            tmpCanvas.width=Options.width;
            tmpCanvas.height=Options.height;
            var tmpContext=tmpCanvas.getContext("2d");
            //--放入临时画布。
            tmpContext.clearRect(0,0,tmpCanvas.width,tmpCanvas.height);
            //context.clearRect(0,0,canvas.width,canvas.height);
            //context.drawImage(image, 0, 0, image.width, image.height, Options.cropLeft, Options.cropTop, Options_image.scaleWidth, Options_image.scaleHeight);
            // context.drawImage(image, 0, 0, image.width, image.height, Options.cropLeft, Options.cropTop, canvas.width, canvas.height);
            drawImageIOSFix(tmpContext,_realImage, 0, 0, _realWidth, _realHeight, 0, 0, _realWidth, _realHeight);


            //--生成新的canvas。
            var _canvas=document.createElement("canvas");

            var _context=_canvas.getContext("2d");
            //.clearRect(0,0,canvas.width,canvas.height);
            //生成一个可以用的缩略图。

            switch(Options.Orientation){
                case 8:
                    // 90 rotate left     --需要90度向左旋转。。那么，这个 PixelYDimension就是宽度了，PixelXDimension就是高度了。
                    _realWidth=YDimension;
                    _realHeight=XDimension;
                    _canvas.width=_realWidth;
                    _canvas.height=_realHeight;
                    _context.translate(parseInt(_realWidth/2),parseInt(_realHeight/2));
                    _context.rotate(-0.5 * Math.PI);
                    _context.drawImage(tmpCanvas,0,0,tmpCanvas.width,tmpCanvas.height,0-Options.transX,0-Options.transY,tmpCanvas.width,tmpCanvas.height);

                    break;
                case 3:
                    //180向左旋转
                    _realWidth=XDimension;
                    _realHeight=YDimension;
                    _canvas.width=_realWidth;
                    _canvas.height=_realHeight;
                    this._scale(_context,_canvas);
                    _context.translate(parseInt(_realWidth/2),parseInt(_realHeight/2));
                    _context.rotate(Math.PI);
                    _context.drawImage(tmpCanvas,0,0,tmpCanvas.width,tmpCanvas.height,0-Options.transX,0-Options.transY,tmpCanvas.width,tmpCanvas.height);
                    break;
                case 6:
                    //90 rotate right 需要向右旋转90度，PixelYDimension就是宽度了，PixelXDimension就是高度了。
                    _realWidth=YDimension;
                    _realHeight=XDimension;
                    _canvas.width=_realWidth;
                    _canvas.height=_realHeight;

                    this._scale(_context,_canvas);
                    _context.translate(parseInt(_realWidth/2),parseInt(_realHeight/2));
                    _context.rotate(0.5 * Math.PI);


                    _context.drawImage(tmpCanvas,0,0,tmpCanvas.width,tmpCanvas.height,0-Options.transX,0-Options.transY,tmpCanvas.width,tmpCanvas.height);
                    break;
                case 1:
                    _canvas.width=_realWidth;
                    _canvas.height=_realHeight;
                    this._scale(_context,_canvas);
                    _context.drawImage(tmpCanvas,0,0,_realWidth,_realHeight,0-Options.transX,0-Options.transY,tmpCanvas.width,tmpCanvas.height);
                    break;
                default:
                    _canvas.width=_realWidth;
                    _canvas.height=_realHeight;
                    this._scale(_context,_canvas);
                    _context.drawImage(tmpCanvas,0,0,_realWidth,_realHeight,0,0,tmpCanvas.width,tmpCanvas.height);
            }

            console.log(_canvas.toDataURL().length);
            var _base64=_canvas.toDataURL("image/jpeg",0.5);
            settings.onFix(_base64);
            //$(document.body).append(_canvas);
            //selection = new Selection("canvas",16,9);
            // selection.drawScene();
            //selection.addListerner();

            return;

        }

    };

    _app.init();

    var returnObject={
        getExif:function(){
            return _exifInfo;
        }

    };

    return returnObject;
};

// $("#myImage").on("click",function(){
//   selectFileImage($("#image")) 
// })
function selectFileImage(fileObj) {
    //alert("selectFileImage");
    var file = fileObj.files['0'];
    //图片方向角 added by lzk
    var Orientation = null;

    if (file) {
        console.log("正在上传,请稍后...");
        $("#upload_bg").css("background","none");
        $("#myImage").attr("src","");
        $("#myImage").attr("src","images/loading.gif");
        var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式
        if (!rFilter.test(file.type)) {
            //showMyTips("请选择jpeg、png格式的图片", false);
            return;
        }

        var blobURL = getObjectURL(file);
        var fix = ImageOrientationFix({
            image:blobURL
            ,onFix:function(base64_str){
                //alert("fix image down!")
                $("#myImage").attr("src",base64_str);
                $(".app-img").css("border","1px #fff solid");
                var img_width = $("#myImage").css("width");
                $("#upload_bg").css({"width":img_width,"height":"264px","margin":0})
                $("#image").css({"height":"264px","width":img_width+100,"z-index":999});
                $("#myImage").css({"z-index":0});
                //AlloyImage(img).ps("vintage").replace(img);            
            }
        });

    }
}
// var img = document.getElementById("myImage");
// img.onload = function(){

// };
$("#myImage").click(function(){
    //alert("click image");
    $("#image").click();
});

//建立一個可存取到該file的url
function getObjectURL(file) {
    var url = null ;
    if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url ;
}

$(".create_crad").on("click",function(){
    if($("#myImage").attr("src") ==""){
        //alert("您还未选择图片");
        return;
    }
    //if($("#myImage").attr("src") ==)
    $(".wrap").css("opacity","0.3");
    $(".wrap").wrap("<div class='loading'><img class='loading_img' src='images/making.gif'/></div>");
    var formData = new FormData();
    var input_arr = $(".dec_text");
    var text_arr = [];
    for(var i=0;i<4;i++){
        if($(input_arr[i]).val()==""){
            $(input_arr[i]).val($(input_arr[i]).attr("placeholder"));
        }
        text_arr[i] = $(input_arr[i]).val();
        formData.append("word"+parseInt(i+1),text_arr[i]);
        console.log(text_arr[i])
    }
    //console.log(formData)
    // lrz($('#image')[0].files[0], {height: 742}, function (results) {
    //lrz($("#myImage").attr("src"), {height: 742}, function (results) {
    //var resultFile = $('#myImage').attr('src');
    var dataURI = $("#myImage").attr("src");
    var mimeString =  dataURI.split(',')[0].split(':')[1].split(';')[0]; // mime类型
    var byteString = atob(dataURI.split(',')[1]); //base64 解码
    var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
    var intArray = new Uint8Array(arrayBuffer); //创建视图
    for (i = 0; i < byteString.length; i += 1) {
        intArray[i] = byteString.charCodeAt(i);
    }

    var blob = new Blob([intArray], { type:  mimeString }); //转成blob

    formData.append('image', blob);
    generate(formData,"http://kcloudtest.iflytek.com/dad_api/image/generate/",function(){
    // generate(formData,"http://cqa.iflytek.com/mum_service/image/generate/",function(){
    //    generate(formData,"http://120.27.154.34:8002/image/generate/");
    });
    //});
})


function generate(formData,serviceUrl,error){
    $.ajax({
        type:'POST',
        data: formData,
        dataType:'json',
        //url:"http://cqa.iflytek.com/mum_service/image/generate/",
        url:serviceUrl,
        cache: false,
        processData: false,
        contentType: false,
        success:function(data){
            console.log(data)
            window.location.href="share.html?name="+data.name;
        },error:function(data){
            if(error){
                error(formData,serviceUrl);
            }
        }
    })
}
